import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { Message } from './entities/message.entity';
import {
  SendMessageDto,
  GetMessagesDto,
  MarkReadDto,
} from './dto/create-message.dto';

@Injectable()
export class MessageService {
  constructor(
    @InjectRepository(Message)
    private messageRepository: Repository<Message>,
  ) {}

  async sendMessage(sendMessageDto: SendMessageDto) {
    const message = this.messageRepository.create({
      ...sendMessageDto,
      send_time: new Date(),
    });
    return this.messageRepository.save(message);
  }

  async getMessages(getMessagesDto: GetMessagesDto) {
    const { user_id, doctor_id } = getMessagesDto;
    return this.messageRepository.find({
      where: [
        { sender_id: user_id, receiver_id: doctor_id },
        { sender_id: doctor_id, receiver_id: user_id },
      ],
      order: { send_time: 'ASC' },
    });
  }

  async markMessagesAsRead(markReadDto: MarkReadDto) {
    return this.messageRepository.update(
      { id: In(markReadDto.message_ids) },
      { is_read: true },
    );
  }
}
